<!--修改行政考核考核模板-->
<template>
  <div class="newCheckContainer">
    <!--图片预览开始-->

    <div class="preViewDiv" v-if="preViewshow">
      <div class="preViewDivTop">
        <div class="custom-indicator" slot="indicator">{{ current + 1 }}/{{photoimg.length}}</div>
        <van-icon name="clear" class="closeable" @click="preViewshow=!preViewshow" />
      </div>
      <van-swipe class="my-swipe" @change="onChange" :show-indicators="false">
        <van-swipe-item v-bind:key="index" v-for="(item,index) in photoimg">
          <van-icon v-if="detailStatu==0" name="delete" class="deleteable" @click="del(current)" />
          <van-image :src="item.url" class="bannerimg" fit="cover" height="100%" width="100%" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <!--图片预览结束-->
    <!--头部bar开始-->
    <CommonBar :options="options"></CommonBar>
    <!--头部bar结束-->
    <div class="divheight"></div>
    <!--考核员指标开始-->
    <div class="zhibiao">
      <p :class="ellipsis?'ellipsis':'unellipsis'" class="zhibiaoitem descontent">
        <span v-for="(item,index) in TemplateKpiTop" :key="index">
          {{item}}
          <br />
        </span>
      </p>
      <p class="showdesc" @click="ela">
        {{ellipsis?'展开':'收起'}}
        <van-icon :name="ellipsis?'arrow-down':'arrow-up'" class="arrowicon" />
      </p>
    </div>
    <!--考核员指标结束-->
    <div class="divheight"></div>
    <!--选行政区开始-->

    <div class="areacontent">
      <van-row gutter="30">
        <van-col span="12">
          <p class="menu">{{de_project_company_name}}</p>
        </van-col>
        <van-col span="12">
          <p class="menu">{{de_project_name}}</p>
        </van-col>
      </van-row>
    </div>
    <!--选行政区结束-->
    <div class="divheight"></div>
    <!--打分开始-->
    <div class="scorecontent">
      <div class="countScoreDiv">
        <div class="countScoreTop">
          <p>
            项目部：
            <span>{{clearnName}}</span>
          </p>
          <p>{{signdate}}</p>
        </div>
      </div>
      <div class="countScoreHeader">
        <van-row>
          <van-col :span="12">考核项名称</van-col>
          <van-col :span="6" class="textcenter">得分</van-col>
          <van-col :span="3" class="textcenter" v-if="detailStatu==0">拍照</van-col>
          <van-col :span="3" class="textright">查看</van-col>
        </van-row>
      </div>
      <div>
        <van-row v-for="(item ,$index) in detailresult" :key="$index" class="rowItem">
          <van-col :span="12">{{item.template_kpi_name}}</van-col>
          <van-col :span="6">
            <input
              type="number"
              v-model="item.score"
              class="scoreinput"
              :disabled="detailStatu==1?true:false"
            />
          </van-col>
          <van-col :span="3" class="textcenter" v-if="detailStatu==0">
            <button
              class="photobut"
              @click="takephoto($index)"
              :disabled="detailStatu==1?true:false"
            >
              <van-image width="22" height="22" :src="takephoto1" style="vertical-align: middle;" />
            </button>
          </van-col>
          <van-col :span="3" class="textright" @click="ViewImg($index)">
            <!-- <van-image
              width="22"
              height="22"
              :src="viewImg1"
              style="vertical-align: middle;"
              v-if="item.photo&&item.photo.length>0 "
            />-->
            <van-image
              width="22"
              height="22"
              :src="item.photo&&item.photo.length>0?viewImg1:viewImghui"
              style="vertical-align: middle;"
            />
          </van-col>
        </van-row>
        <van-action-sheet v-model="takephotoshow" :actions="actions" @select="takephotoSelect" />
      </div>
      <p class="allcount">
        总分:
        <span>{{sumconunt}}</span>
      </p>
      <div class="buttonbot" v-if="detailStatu==0  &&user_role_id==10">
        <p class="pass" @click="savedata">保存</p>
        <p class="refuse" @click="submit">提交</p>
      </div>
    </div>
    <!--加载框开始-->
    <van-overlay :show="showloading">
      <div class="wrapper">
        <div class="loadingcont">
          <van-loading size="24px" vertical>{{loaddingText}}</van-loading>
        </div>
      </div>
    </van-overlay>
    <!--加载框结束-->
    <!--打分结束-->
  </div>
</template>
<script>
import { compressImage } from "../../common/compressImage";
import { Dialog } from "vant";
import CommonBar from "../../common/commonBar";
import { mapState } from "vuex";
export default {
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization,
      user_department_type: state => state.userData.department_type, //人员类型
      user_department_id: state => state.userData.department_id, // 人员id
      user_group_department_id: state => state.userData.group_department_id,
      user_project_company_id: state => state.userData.project_company_id,
      user_project_id: state => state.userData.project_id,
      user_role_id: state => state.userData.role_id
    })
  },
  data() {
    return {
      value1: 0,
      option1: [{ text: "", value: 0 }],
      ellipsis: true,
      takephoto1: require("../../../../static/image/takephoto.png"),
      viewImg1: require("../../../../static/image/viewImg.png"),
      viewImghui: require("../../../../static/image/viewimghui.png"),
      //加载框
      showloading: false,
      loaddingText: "加载中",
      //公共bar
      options: {
        type: "icon",
        centerText: "行政考核",
        iconNname: "wap-home",
        lefttype: "left"
      },
      TemplateKpiTop: [], //指标内容
      //项目管理部
      GroupDepartment: "1",
      GroupDepartmentcolumns: [],
      //项目公司
      ProjectCompany: "",
      ProjectCompanycolumns: [],
      //行政考核
      Project: "",
      Projectcolumns: [],
      //片区
      value1: 0,
      option1: [{ text: "", value: 0 }],
      // District: 0,
      // Districtcolumns: [{ text: "", value: 0 }],
      clearnName: "", //行政考核姓名
      district_id: "", //行政考核所在片区
      signdate: "", //当前日期
      scoreinput: "",
      photo: [],
      detailresult: [],
      //相机
      actions: [
        { name: "相机", id: "1" },
        { name: "图库", id: "2" },
        { name: "取消", id: "3" }
      ],
      takephotoshow: false,
      currentLng: "",
      currentLat: "",
      currentDateTime: "",
      IMGURL: "",
      countindex: "",
      //参数赋值
      group_department_id: "",
      project_company_id: "",
      project_id: "",
      district_id1: "",
      duty_id: "",
      template_id: "",
      detailId: "",
      detailStatu: "",
      updateId: "",
      addrcode: "",
      address: "",
      //预览图片带删除
      preViewshow: false,
      current: 0,
      photoimg: [],
      sumconunt: 0,
      arrchenge: "",
      de_project_company_name: "",
      de_project_name: ""
    };
  },
  created() {
    //行政考核考核详情带过来的参数
    this.detailId = this.$route.query.id;
    this.detailStatu = this.$route.query.statu;
    this.clearnDetail();
    // this.initFirst();
    this.showDate();
  },
  //当拍照改变后photo数组就为空
  watch: {
    countindex(newval, oldval) {
      console.log(newval, oldval);
      this.photo = [];
    },
    current: function(newval, oldval) {
      console.log("current", newval, oldval);
    },
    detailresult: {
      handler: function(newVal, oldval) {
        if (oldval.length <= 0) {
          this.arrchenge = false;
        } else {
          this.arrchenge = true;
        }
        console.log("监听", newVal);
        let new_arr = newVal.map(obj => {
          return obj.score;
        });
        console.log(new_arr);
        var r = new_arr.filter(function(s) {
          return s && s.trim();
        });
        console.log(r);
        var sum = 0;
        for (let i = 0; i < r.length; i++) {
          sum += parseInt(r[i]);
        }
        console.log(sum);
        this.sumconunt = sum;
        // var initialValue = 0;
        // var sum = newVal.reduce(function(accumulator, currentValue) {
        //   if(currentValue.score)
        //   return accumulator + parseInt(currentValue.score);
        // }, initialValue);
        // this.sumconunt=sum
        // console.log(sum); // logs 6
      },
      deep: true //深度监听
    }
  },
  destroyed() {
    var that = this;
    document.removeEventListener("backbutton", that.backbutton, false);
  },
  mounted() {
    if (this.detailStatu == 0 && this.user_role_id == 10) {
      var that = this;
      document.addEventListener("backbutton", that.backbutton, false);
    }
  },
  methods: {
    ela() {
      this.ellipsis = !this.ellipsis;
    },
    /**
     * onChange预览照片时的轮播方法
     * del删除预览照片
     */
    onChange(index) {
      this.current = index;
    },
    backbutton() {
      if (this.arrchenge) {
        Dialog.confirm({
          title: "提示",
          message: "内容未保存，是否返回"
        })
          .then(() => {
            history.back();
          })
          .catch(() => {
            // on cancel
          });
      } else {
        history.back();
      }
    },
    del(id) {
      Dialog.confirm({
        title: "提示",
        message: "是否删除该照片"
      })
        .then(() => {
          this.photoimg.splice(id, 1);
          this.current = 0;
          if (this.photoimg.length == 0) {
            this.current = -1;
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    //行政考核考核详情
    clearnDetail() {
      this.$toast.loading({
        mask: true,
        message: "加载中...",
        duration: 5000
      });
      var params = { token: this.token, id: this.detailId };
      this.$http
        .get(
          `${this.$basePath}?service=App.Project.GetAdministrativeCheckDetails&api=86`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            this.$toast.clear();
            console.log("行政考核详情", res);
            this.group_department_id = res.data.group_department_id;
            this.project_company_id = res.data.project_company_id;
            this.project_id = res.data.project_id;
            this.addrcode = res.data.addrcode;
            this.address = res.data.address;
            this.de_project_company_name = res.data.project_company_name;
            this.de_project_name = res.data.project_name;
            this.option1[0].text = res.data.address;
            console.log("1", this.Districtcolumns);
            this.template_id = res.data.template_id;
            this.District = res.data.address;
            this.clearnName = res.data.project_name;
            this.detailresult = res.data.result;
            this.TemplateKpiTop = res.data.remark;
            this.updateId = res.data.id;
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //拍照事件
    takephoto(template_id) {
      this.takephotoshow = true;
      this.countindex = template_id;
    },
    //选中图片方式，1是相机，2是图库
    takephotoSelect(item) {
      this.takephotoshow = false;
      if (item.id == 3) {
        this.$toast({ message: "取消上传图片" });
      } else if (
        this.detailresult[this.countindex].photo &&
        this.detailresult[this.countindex].photo.length >= 5
      ) {
        this.$toast({ message: "不能上传超过5张" });
      } else {
        this.$nextTick(() => {
          this.getLoation();
        });
        this.showTime(); //获取当前时间
        this.cameraTakePicture(item.id); //调用相机
      }
    },

    //拍照
    cameraTakePicture(mySourceType) {
      //把缓存里的takephoto里的丢进onsuces
      let that = this;
      navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: mySourceType
      });

      function onSuccess(imageData) {
        var imageurl = "data:image/jpeg;base64," + imageData;
        //拿经纬度
        var lat = localStorage.getItem("currentLat");
        var lng = localStorage.getItem("currentLng");
        var ret = {};
        ret.createtime = that.currentDateTime;
        ret.position = { lon: lng, lat: lat };
        //查看大小
        var str = imageData;
        var equalIndex = str.indexOf("=");
        if (str.indexOf("=") > 0) {
          str = str.substring(0, equalIndex);
        }
        var strLen = str.length;
        var fileSize = strLen - (strLen / 8) * 2;
        var size = (fileSize / 1024).toFixed(2);
        if (parseInt(size) > 1024) {
          compressImage(imageurl, {
            width: 200, // 压缩后图片的宽
            quality: 0.4 // 压缩后图片的清晰度，取值0-1，不传默认为0.7，值越小，所绘制出的图像越模糊
          }).then(result => {
            ret.url = result;
            that.photo.push(ret);
            that.detailresult[that.countindex].photo = that.photo;
            that.$forceUpdate();
          });
        } else {
          ret.url = imageurl;
          that.photo.push(ret);
          that.detailresult[that.countindex].photo = that.photo;
          that.$forceUpdate();
        }
      }

      function onFail(message) {
        this.$toast({ message: message });
      }
    },
    //显示图片弹窗
    ViewImg(index) {
      var array = this.detailresult[index].photo;
      if (array === undefined || array.length == 0) {
        this.$toast({ message: "未上传照片" });
      } else {
        this.photoimg = this.detailresult[index].photo;
        console.log("弹出数组", this.photoimg);
        this.preViewshow = true;
        this.current = 0;
      }
    },

    //获取当前经纬度
    getLoation() {
      let _this = this;
      var geolocation = new BMap.Geolocation();
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          const myGeo = new BMap.Geocoder();
          myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), data => {
            if (data.addressComponents) {
              var result = data.addressComponents;
              var pathlocation = {
                creditLongitude: r.point.lng, // 经度
                creditLatitude: r.point.lat, // 纬度
                creditProvince: result.province || "", // 省
                creditCity: result.city || "", // 市
                creditArea: result.district || "", // 区
                creditStreet:
                  (result.street || "") + (result.streetNumber || "") // 街道
              };
              _this.currentLng = pathlocation.creditLongitude;
              _this.currentLat = pathlocation.creditLatitude;
              localStorage.setItem("currentLng", _this.currentLng);
              localStorage.setItem("currentLat", _this.currentLat);
            }
          });
        }
      });
    },
    //获取当前时间
    showTime() {
      var d = new Date();
      this.currentDateTime =
        d.getFullYear() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate() +
        " " +
        d.getHours() +
        ":" +
        d.getMinutes() +
        ":" +
        d.getSeconds();
    },

    /*行政考核*/
    //显示项目管理部列表
    initFirst() {
      var params = { token: this.token, group_department_id: 1 };
      this.$http
        .get(
          `${this.$basePath}?service=App.Organizational.ListGroupDepartment&api=84`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            console.log("行政考核列表", res);
            var result = res.data.map(o => {
              return {
                text: o.name,
                value: o.id
              };
            });
            console.log("公司", this.group_department_id);
            this.GroupDepartmentcolumns = result;
            var params = {
              group_department_id: 1,
              token: this.token
            };
            this.initSencond(params);
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    /**项目公司 */
    initSencond(params) {
      this.$http
        .get(
          `${this.$basePath}?service=App.Organizational.ListProjectCompany&api=84`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            console.log("项目公司列表", res);
            var result = res.data.map(o => {
              return {
                text: o.name,
                value: o.id
              };
            });
            this.ProjectCompanycolumns = result;
            if (this.ProjectCompanycolumns.length == 0) {
              var ret = {};
              ret.text = "暂无数据";
              ret.value = 0;
              result.push(ret);
              this.ProjectCompany = result[0].value;
            } else {
              this.ProjectCompany = this.project_company_id;
            }
            var params = {
              project_company_id: this.project_company_id,
              token: this.token
            };
            this.initThird(params);
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },

    /**行政考核 */
    initThird(params) {
      this.$http
        .get(
          `${this.$basePath}?service=App.Organizational.ListProject&api=84`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            console.log("行政考核列表", res);
            var result = res.data.map(o => {
              return {
                text: o.name,
                value: o.id
              };
            });
            this.Projectcolumns = result;
            if (this.Projectcolumns.length == 0) {
              var ret = {};
              ret.text = "暂无数据";
              ret.value = 0;
              result.push(ret);
              this.Project = result[0].value;
            } else {
              this.Project = this.project_id;
            }
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },

    /*提交分数事件*/
    postdata(params) {
      this.$http
        .post(
          `${this.$basePath}?service=App.Project.UpdateAdministrativeCheck&api=86`,
          params
        )
        .then(res => {
          if (res.ret == 200) {
            this.$toast({ message: res.msg });
            this.showloading = false;
            console.log("提交分数", res);
            //提交后清空数据
            this.$router.push({
              //核心语句
              path: "/administrativeList" //跳转的路径
            });
          } else {
            this.$toast({ message: res.msg });
            this.showloading = false;
          }
        });
    },
    //数据保存中
    savedata() {
      let result = this.detailresult.find(obj => {
        return obj.score == "";
      });
      console.log(result);
      if (result != undefined) {
        this.$toast({ message: "请填写完整分数", duration: 2000 });
      } else if (this.sumconunt > 100) {
        this.$toast({ message: "总分超过100分，请重新打分" });
      } else {
        this.loaddingText = "数据保存中...";
        this.showloading = true;
        console.log("kpi", this.detailresult);
        var params = {
          token: this.token,
          id: this.updateId,
          group_department_id: 1,
          project_company_id: this.project_company_id,
          project_id: this.project_id,
          result: JSON.stringify(this.detailresult),
          statu: 0,
          template_id: this.template_id
        };
        console.log("params", params);
        this.postdata(params);
      }
    },
    //数据提交
    submit() {
      let result = this.detailresult.find(obj => {
        return obj.score == "";
      });
      console.log(result);
      if (result != undefined) {
        this.$toast({ message: "请填写完整分数", duration: 2000 });
      } else if (this.sumconunt > 100) {
        this.$toast({ message: "总分超过100分，请重新打分" });
      } else {
        this.loaddingText = "数据提交中...";
        this.showloading = true;
        console.log("kpi", this.detailresult);
        var params = {
          token: this.token,
          id: this.updateId,
          group_department_id: 1,
          project_company_id: this.project_company_id,
          project_id: this.project_id,
          result: JSON.stringify(this.detailresult),
          statu: 1,
          template_id: this.template_id
        };
        console.log("params", params);
        this.postdata(params);
      }
    },
    //系统日期
    showDate() {
      var d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let day = d.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      this.signdate = year + "-" + month + "-" + day;
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../../assets/css/check";
</style>